package cn.dckeji.gameBox.common.utils;

import com.alipay.api.request.AlipayOpenPublicUserFollowQueryRequest;
import com.alipay.api.response.AlipayOpenPublicUserFollowQueryResponse;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.setting.dialect.Props;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayOpenPublicQrcodeCreateRequest;
import com.alipay.api.response.AlipayOpenPublicQrcodeCreateResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Lucas
 * @date 2018/3/8
 * @package cn.dckeji.gameBox.common.utils
 * @Description
 */
public class AliPayUtil {

    private static final Logger LOGGER = Logger.getLogger(AliPayUtil.class);

    /**
     * 将异步通知的参数转化为Map
     * @param request
     * @return {Map<String, String>}
     */
    public static Map<String, String> toMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }


    public static String encryptAndSign(String bizContent, String alipayPublicKey, String cusPrivateKey, String charset,
                                        boolean isEncrypt, boolean isSign, String signType) throws AlipayApiException {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isEmpty(charset)) {
            charset = AlipayConstants.CHARSET_GBK;
        }
        sb.append("<?xml version=\"1.0\" encoding=\"" + charset + "\"?>");
        if (isEncrypt) {// 加密
            sb.append("<alipay>");
            String encrypted = AlipaySignature.rsaEncrypt(bizContent, alipayPublicKey, charset);
            sb.append("<response>" + encrypted + "</response>");
            sb.append("<encryption_type>AES</encryption_type>");
            if (isSign) {
                String sign = AlipaySignature.rsaSign(encrypted, cusPrivateKey, charset, signType);
                sb.append("<sign>" + sign + "</sign>");
                sb.append("<sign_type>");
                sb.append(signType);
                sb.append("</sign_type>");
            }
            sb.append("</alipay>");
        } else if (isSign) {// 不加密，但需要签名
            sb.append("<alipay>");
            sb.append("<response>" + bizContent + "</response>");
            String sign = AlipaySignature.rsaSign(bizContent, cusPrivateKey, charset, signType);
            sb.append("<sign>" + sign + "</sign>");
            sb.append("<sign_type>");
            sb.append(signType);
            sb.append("</sign_type>");
            sb.append("</alipay>");
        } else {// 不加密，不加签
            sb.append(bizContent);
        }
        return sb.toString();
    }

    /**
     * 创建二维码
     * @param type
     * @param codeid
     */
    public static AlipayOpenPublicQrcodeCreateResponse createCode(Integer type, String codeid) throws AlipayApiException {
        Props props = new Props("alipy.properties","utf-8");
        String appid = props.getStr("ALI_APPID");
        String pubkey = props.getStr("ALI_PUBKEY");
        String prikey = props.getStr("ALI_PRIKEY");
        String qrcode_goto_url = props.getStr("QRCODE_GOTO_URL");
        qrcode_goto_url+="?type="+type+"&codeid="+codeid;

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appid,prikey,"json","utf-8",pubkey,"RSA2");
        AlipayOpenPublicQrcodeCreateRequest request = new AlipayOpenPublicQrcodeCreateRequest();
        if (type==1) {
            request.setBizContent("{" +
                    "\"code_info\":{" +
                    "\"scene\":{" +
                    "\"scene_id\":\"1234\"" +
                    "      }," +
                    "\"goto_url\":\""+qrcode_goto_url+"\"" +
                    "    }," +
                    "\"code_type\":\"TEMP\"," +
                    "\"expire_second\":\"1800\"," +
                    "\"show_logo\":\"Y\"" +
                    "  }");
        }else {
            request.setBizContent("{" +
                    "\"code_info\":{" +
                    "\"scene\":{" +
                    "\"scene_id\":\"1234\"" +
                    "      }," +
                    "\"goto_url\":\""+qrcode_goto_url+"\"" +
                    "    }," +
                    "\"code_type\":\"PERM\"," +
                    "\"show_logo\":\"Y\"" +
                    "  }");
        }

        AlipayOpenPublicQrcodeCreateResponse response = alipayClient.execute(request);
        LOGGER.info("创建二维码的返回值:"+ BeanUtil.beanToMap(response));
        return response;
    }

    public static String isFllow(String userid) throws AlipayApiException {
        Props props = new Props("alipy.properties","utf-8");
        String appid = props.getStr("ALI_APPID");
        String pubkey = props.getStr("ALI_PUBKEY");
        String prikey = props.getStr("ALI_PRIKEY");
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appid,prikey,"json","utf-8",pubkey,"RSA2");
        AlipayOpenPublicUserFollowQueryRequest request = new AlipayOpenPublicUserFollowQueryRequest();
        request.setBizContent("{" +
                "\"user_id\":\""+userid+"\"" +
                "}");
        AlipayOpenPublicUserFollowQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            return response.getIsFollow();
        } else {
            LOGGER.info("查询用户是否关注异常"+response);
            return "";
        }
    }

}
